#!/bin/bash
# *************************************
# 功能: k8s集群cri-docker服务
# 作者: 肖晨光
# 联系: 1819329667@qq.com
# 版本: v0.1
# 日期: 2023-07-31
# *************************************
cri_hostlist="$*"

# 获取CRI软件
get_cri_softs(){
	  # 从github上获取最新版本的cri软件
	[ ! -d "${softs_dir}" ] && mkdir "${softs_dir}"
	if [ ! -f "${softs_dir}/${cri_softs_name}" ] ; then
		cd "${softs_dir}"
		wget "${cri_softs_url}"
		tar xf "${cri_softs_name}" -C /tmp
	fi
}

# 定制CRI配置
create_cri_conf(){
	  # 定制cri-dockerd的service配置文件
	  [ -f "/tmp/${cri_service_conf}" ] || cat > "/tmp/${cri_service_conf}" <<-eof
		  [Unit]
		  Description=CRI Interface for Docker Application Container Engine
		  Documentation=https://docs.mirantis.com
		  After=network-online.target firewalld.service docker.service
		  Wants=network-online.target
		  [Service]
		  Type=notify
		  ExecStart=/usr/local/bin/cri-dockerd --pod-infra-container-image=registry.cn-hangzhou.aliyuncs.com/google_containers/pause:3.9 --network-plugin=cni --cni-conf-dir=/etc/cni/net.d --cni-bin-dir=/opt/cni/bin --container-runtime-endpoint=unix:///var/run/cri-dockerd.sock --cri-dockerd-root-directory=/var/lib/dockershim --docker-endpoint=unix:///var/run/docker.sock --cri-dockerd-root-directory=/var/lib/docker
		  ExecReload=/bin/kill -s HUP $MAINPID
		  TimeoutSec=0
		  RestartSec=2
		  Restart=always
		  StartLimitBurst=3
		  StartLimitInterval=60s
		  LimitNOFILE=infinity
		  LimitNPROC=infinity
		  LimitCORE=infinity
		  TasksMax=infinity
		  Delegate=yes
		  KillMode=process
		  [Install]
		  WantedBy=multi-user.target
		  eof
		    # 定制cri-dockerd的socket配置文件
		    [ -f "/tmp/${cri_socket_conf}" ] || cat > "/tmp/${cri_socket_conf}" <<-eof
			[Unit]
			Description=CRI Docker Socket for the API
			PartOf=cri-docker.service

			[Socket]
			ListenStream=/var/run/cri-dockerd.sock
			SocketMode=0660
			SocketUser=root
			SocketGroup=docker

			[Install]
			WantedBy=sockets.target
			eof
}

# 传输CRI配置
scp_cri_conf(){
	  # 传输cri配置文件到所有的k8s节点主机
	  for ip in $(eval echo "${cri_hostlist}") ; do
		scp "/tmp/${cri_name}/${cri_name}" "${login_user}@${ip}:${service_bin_dir}/"
		scp "/tmp/${cri_service_conf}" "${login_user}@${ip}:${service_conf_dir}/"
		scp "/tmp/${cri_socket_conf}" "${login_user}@${ip}:${service_conf_dir}/"
		done
}

# 检测CRI服务
check_cri_serv(){
	# 检测当前主机cri环境是否正常
	host_addr="$1"
	local status=$(ssh "${login_user}@${host_addr}" "systemctl is-active ${cri_service_conf}")
	if [ "${status}" == "active" ]; then
	echo -e "\e[32m${host_addr} 主机CRI服务部署成功\e[0m"
	else
	echo -e "\e[31m${host_addr} 主机CRI服务部署失败\e[0m"
	exit
	fi
}

# 启动CRI服务
deploy_cri_serv(){
	# 将所有的k8s节点主机上的cri服务启动起来
	for ip in $(eval echo "${cri_hostlist}") ; do
	ssh "${login_user}@${ip}" "systemctl daemon-reload;systemctl enable ${cri_service_conf}" 
	ssh "${login_user}@${ip}" "systemctl restart ${cri_service_conf}"
	check_cri_serv "${ip}"
	done
}


# 主函数
main(){
	get_cri_softs
	create_cri_conf
	scp_cri_conf
	deploy_cri_serv
}

# 执行主函数
main
